package parser

import (
	"learngo/crawler/engine"
	"regexp"
	"strings"
)

var (
	profileRe = regexp.MustCompile(
		`<a href="(http://album.zhenai.com/u/[0-9]+)"[^>]*>([^<]+)</a>`)
	cityurlRe = regexp.MustCompile(`href="(http://www.zhenai.com/zhenghun/[^"]+)"`)
)

func ParseCity(contents []byte, _ string) engine.ParseResult {
	// 解析每个城市中对象列表

	matches := profileRe.FindAllSubmatch(contents, -1) // 子匹配查询
	result := engine.ParseResult{}                     // 页面解析结果
	old := "http"
	new := "https"
	for _, m := range matches {
		name := string(m[2]) // 拷贝m[2]，否则循环出来后，m[2]指针在最后一个人的名字，名字也一样了
		//result.Items = append(result.Items, "User " + name)  // item存入城市名
		url := strings.Replace(string(m[1]), old, new, 1)
		result.Requests = append(result.Requests, engine.Request{
			Url:    url, // requests 存入URL和解析器
			Parser: NewProfileParser(name),
		})
	}

	matches = cityurlRe.FindAllSubmatch(contents, -1)
	for _, m := range matches {
		result.Requests = append(result.Requests, engine.Request{
			Url:    string(m[1]),
			Parser: engine.NewFuncParser(ParseCity, "ParseCity"),
		})
	}
	return result
}
